package com.gzxw.mogublog.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.commons.entity.Blog;
import com.gzxw.mogublog.commons.entity.BlogSort;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.xo.mapper.BlogMapper;
import com.gzxw.mogublog.xo.mapper.BlogSortMapper;
import com.gzxw.mogublog.xo.service.BlogService;
import com.gzxw.mogublog.xo.service.BlogSortService;
import com.gzxw.mogublog.xo.vo.BlogSortVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BlogSortServiceImpl extends ServiceImpl<BlogSortMapper, BlogSort> implements BlogSortService {

    @Autowired
    private BlogService blogService;


    @Override
    public IPage<BlogSort> getList(BlogSortVO blogSortVO) {

        QueryWrapper<BlogSort> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(blogSortVO.getKeyword()) && !StringUtils.isEmpty(blogSortVO.getKeyword().trim())) {
            queryWrapper.like("sort_name", blogSortVO.getKeyword());
        }
        if (StringUtils.isNotEmpty(blogSortVO.getOrderByAscColumn())) {
            queryWrapper.orderByAsc(StringUtils.underLine(new StringBuffer(blogSortVO.getOrderByAscColumn())).toString());
        }else if (StringUtils.isNotEmpty(blogSortVO.getOrderByDescColumn())){
            queryWrapper.orderByDesc(StringUtils.underLine(new StringBuffer(blogSortVO.getOrderByDescColumn())).toString());

        }else {
            queryWrapper.orderByDesc("sort","create_time");
        }
        Page<BlogSort> page = new Page<>();
        page.setCurrent(blogSortVO.getCurrentPage());
        page.setSize(blogSortVO.getPageSize());

        queryWrapper.eq("status", 1);

        return this.page(page, queryWrapper);
    }

    @Override
    public String addBlogSort(BlogSortVO blogSortVO) {

        // 判断当前分类是否存在
        QueryWrapper<BlogSort> queryWrapper = new QueryWrapper<>();
        String sortName = blogSortVO.getSortName();
        queryWrapper.eq("sort_name", sortName);
        queryWrapper.eq("status", 1);
        int count = this.count(queryWrapper);
        if (count > 0) {
            return "当前分类已经存在!";
        }
        BlogSort blogSort = new BlogSort();
        blogSort.setSortName(blogSortVO.getSortName());
        blogSort.setSort(blogSortVO.getSort());
        blogSort.setContent(blogSortVO.getContent());
        blogSort.setStatus(1);
        int insert = baseMapper.insert(blogSort);

        return insert > 0 ? "添加成功" : "添加失败";
    }

    @Override
    public String editBlogSort(BlogSortVO blogSortVO) {

        BlogSort blogSort = new BlogSort();
        blogSort.setSortName(blogSortVO.getSortName());
        blogSort.setSort(blogSort.getSort());
        blogSort.setContent(blogSort.getContent());
        blogSort.setUpdateTime(new Date());
        boolean update = blogSort.updateById();
        // 删除和博客相关的Redis缓存
        //  blogService.deleteRedisByBlogSort();
        return update ? "更新成功" : "更新失败!";
    }

    @Override
    public String deleteBatch(List<BlogSortVO> blogSortVOList) {

        if (blogSortVOList.size() <= 0) {
            return "传入参数有误";
        }

        // 查询这些分类下是否有博客
        List<String> uids = new ArrayList<>();
        blogSortVOList.forEach(item -> uids.add(item.getUid()));

        QueryWrapper<Blog> blogWrapper = new QueryWrapper<>();
        blogWrapper.eq("status", 1);
        blogWrapper.in("blog_sort_uid", uids);
        int count = blogService.count(blogWrapper);
        if (count > 0) {
            return "该分类下仍然有博客，请先删除!";
        }

        Collection<BlogSort> blogSorts = this.listByIds(uids);
        blogSorts.forEach(item -> {
            item.setStatus(0);
            item.setUpdateTime(new Date());
        });
        boolean deleteBatch = this.updateBatchById(blogSorts);

        return deleteBatch ? "删除成功" : "删除失败!";
    }

    @Override
    public String stickBlogSort(BlogSortVO blogSortVO) {
        BlogSort blogSort = this.getById(blogSortVO.getUid());

        QueryWrapper<BlogSort> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("sort");
        queryWrapper.last("limit 1");
        BlogSort maxSortBlogSort = this.getOne(queryWrapper);

        if (blogSortVO.getUid().equals(maxSortBlogSort.getUid())) {
            return "当前分类已经在顶端";
        }

        int newSort = maxSortBlogSort.getSort() + 1;
        blogSort.setSort(newSort);
        blogSort.setUpdateTime(new Date());
        boolean stickBlogSort = blogSort.updateById();
        return stickBlogSort ? "操作完成" : "操作失败";
    }

    @Override
    public String blogSortByClickCount() {
        QueryWrapper<BlogSort> blogSortQueryWrapper = new QueryWrapper<>();
        blogSortQueryWrapper.eq("status", 1);
        blogSortQueryWrapper.orderByDesc("click_count");

        List<BlogSort> blogSorts = this.list(blogSortQueryWrapper);

        blogSorts.forEach(item -> {
            item.setSort(item.getClickCount());
            item.setUpdateTime(new Date());
        });
        this.updateBatchById(blogSorts);

        return "操作成功";
    }

    @Override
    public String blogSortByCite() {

        // 定义 key：Uid  value：引用量
        Map<String, Integer> map = new HashMap<>();

        // 设置查询博客分类的条件
        QueryWrapper<BlogSort> blogSortQueryWrapper = new QueryWrapper<>();
        blogSortQueryWrapper.eq("status", 1);
        List<BlogSort> blogSortList = this.list(blogSortQueryWrapper);

        // 初始化所有标签的引用量
        blogSortList.forEach(item -> {
            map.put(item.getUid(), 0);
        });

        // 查询已经发布出博客的数量
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("is_publish", 1);
        blogQueryWrapper.eq("status", 1);
        // 过滤content字段
        blogQueryWrapper.select(Blog.class, i -> !i.getProperty().equals("content"));
        List<Blog> blogList = blogService.list(blogQueryWrapper);
        // 遍历每个博客，如果存在分类，则从map中取出该分类的值并+1
        blogList.forEach(item -> {
            String blogSortUid = item.getBlogSortUid();
            Integer count = map.get(blogSortUid);
            if (count != null) {
                map.put(blogSortUid, count + 1);
            } else {
                map.put(blogSortUid, 0);
            }
        });

        // 遍历blogSortList重新设置他们的sort字段
        blogSortList.forEach(item -> {
            item.setSort(map.get(item.getUid()));
            item.setUpdateTime(new Date());
        });

        boolean isblogSortByCite = this.updateBatchById(blogSortList);

        return isblogSortByCite ? "操作成功" : "操作失败";
    }
}
